<template>
    <div>
        <el-form :model="updateRole" status-icon ref="roleForm" label-width="100px" label-position="left"
            style="width:90%" :rules="rules">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="updateRole.name" placehilder="请输入角色名称"></el-input>
            </el-form-item>
        </el-form>
        <el-tree :data="authList" show-checkbox node-key="index" :default-expand-all="true"
            :default-checked-keys="checkedKeys" @check-change="handleCheckChange"
            ref="tree"    
        >
        </el-tree>
    </div>
</template>

<script>
var set = new Set();
import menuList from "@/utils/NavigationLists"
export default {
 data () {
 return {
    rules:{
         name: [{ required: true, message: '角色名称必须输入', trigger: ['blur','change'] }]
    },
    updateRole:{},//更新后的角色名
    authList:[],//存储导航栏信息
    checkedKeys:[]//当前角色权限
 }
 },
props:["role"],
components: {},
mounted(){
    this.updateRole = {...this.role}
    this.authList = this.getAuthNodes(menuList)
    this.checkedKeys = this.role.menus;
    set = new Set([...this.checkedKeys])
},
 methods: {
    // 获取所有导航项
     getAuthNodes(menuList){
        return menuList.map(item => {
            if(!item.children){
                return{
                    index:item.index,
                    label:item.title
                } 
            }else{
                return{
                    index: item.index,
                    label: item.title,
                    children:this.getAuthNodes(item.children)
                }
            }
        })
     },
    //节点变化时调用
     handleCheckChange(data,checked,indeterminate){
        if(checked){
            set.add(data.index)
            // console.log(set, 'z');
            // console.log(data, checked, indeterminate);
        }else{
            // console.log(set);
            set.delete(data.index)
            // console.log(set, 'c');
        }
        
     },
    //子组件传给父组件
     getMenus(){
        // console.log(set);
        this.checkedKeys = [...set]
        set.clear();
        this.updateRole.menus = this.checkedKeys
        return this.updateRole
     }
 },
//bug修复设置角色权限显示时显示上一项角色权限
 watch:{
    role(val){
        if(val){
            this.$nextTick(()=>{
                this.updateRole = {...val};
                this.checkedKeys = val.menus;
                set = new Set([...this.checkedKeys])
                // console.log(this.checkedKeys);
                this.$refs["tree"].setCheckedKeys(this.checkedKeys);
            })
        }
    }
 }
}
</script>

<style scoped>
</style>